/*
 * StartupDialog.java
 *
 * Created on September 29, 2008, 4:19 PM
 *
 * Copyright 2008 David D. Emory
 * 
 * This file is part of Five Points. See <http://www.fpdev.org> for
 * additional information regarding the project.
 * 
 * Five Points is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Five Points is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Five Points.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.fpdev.apps.admin.gui.dialogs;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.io.File;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.fpdev.core.FPEngine;
import org.fpdev.core.DataPackage;
import org.fpdev.core.SysProps;
import org.fpdev.apps.admin.gui.ImagePanel;
import org.fpdev.apps.admin.shp.ShapefileIO;
import org.fpdev.util.gui.GUIFactory;
import org.fpdev.util.gui.UneditableTableModel;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author demory
 */
public class StartupDialog extends JDialog implements ActionListener {
  
  private Properties sysProps_;
  private String initDP_;
  
  private JButton proceedBtn_, cancelBtn_, newBtn_;
  
  private DPTable dpTable_;
  
  public StartupDialog(Properties sysProps) {
    super((JFrame) null, "Five Points Startup", true);
    sysProps_ = sysProps;
    
    JPanel mainPanel = new JPanel(new BorderLayout());
    
    
    JPanel headerRow = GUIFactory.newRowPanel();
    headerRow.setBackground(Color.white);
    headerRow.setPreferredSize(new Dimension(320, 60));
    headerRow.add(new ImagePanel(sysProps_.getProperty(SysProps.FP_HOME)+"img"+File.separator+"fpheader.png"));  
    headerRow.add(Box.createHorizontalGlue());
    JLabel lbl = GUIFactory.newLabel("v"+FPEngine.VERSION);
    lbl.setBorder(new EmptyBorder(30,0,0,10));
    headerRow.add(lbl);
    
    JPanel centerPanel = new JPanel(new BorderLayout());
    newBtn_ = GUIFactory.newButton("Create New...", 80, this);// new JButton("Create New...");
    JPanel centerHeader = new JPanel(new BorderLayout());
    centerHeader.add(new JLabel("Select a Data Package:"), BorderLayout.WEST);
    centerHeader.add(newBtn_, BorderLayout.EAST);
    centerHeader.setBorder(new EmptyBorder(0, 0, 5, 0));
    
    dpTable_ = new DPTable();    
    
    centerPanel.add(centerHeader, BorderLayout.NORTH);
    centerPanel.add(new JScrollPane(dpTable_), BorderLayout.CENTER);
    centerPanel.setBorder(new EmptyBorder(5, 10, 5, 10));
    
    proceedBtn_ = new JButton("Proceed");
    proceedBtn_.addActionListener(this);
    proceedBtn_.setEnabled(false);
    
    cancelBtn_ = new JButton("Cancel");
    cancelBtn_.addActionListener(this);
    
    JPanel buttonRow = GUIFactory.newRowPanel();
    buttonRow.add(Box.createHorizontalGlue());
    buttonRow.add(proceedBtn_);
    buttonRow.add(Box.createHorizontalStrut(5));
    buttonRow.add(cancelBtn_);
    buttonRow.add(Box.createHorizontalGlue());    
    buttonRow.setBorder(new EmptyBorder(5, 5, 5, 5));

    mainPanel.add(headerRow, BorderLayout.NORTH);
    mainPanel.add(centerPanel, BorderLayout.CENTER);
    mainPanel.add(buttonRow, BorderLayout.SOUTH);
    
    getContentPane().add(mainPanel);
    setSize(400,300);
    setLocationRelativeTo(null);
    setAlwaysOnTop(true);        
    setVisible(true);
  }
  
  public String getInitDPName() { return initDP_; }

  public void actionPerformed(ActionEvent e) {
    if(e.getSource() == proceedBtn_) proceed();
    
    if(e.getSource() == cancelBtn_) setVisible(false); 
    
    if(e.getSource() == newBtn_) new CreateDataPackageDialog(this);
  }

  public void proceed() {
    initDP_ = dpTable_.getValueAt(dpTable_.getSelectedRow(), 0).toString();
    setVisible(false);
  }

  public void createDataPackage(String name, String desc, double initX, double initY) {
    DataPackage.initDP(name, desc, initX, initY, sysProps_);
    //dpTable_.updateData();
    initDP_ = name;
    setVisible(false);
  }

  public void createDataPackage(String name, String desc, File shapefile) {
    Point2D pt = ShapefileIO.getMidpoint(shapefile);
    DataPackage.initDP(name, desc, pt.getX(), pt.getY(), sysProps_);
    sysProps_.setProperty(SysProps.INIT_SHP, shapefile.getPath());
    //dpTable_.updateData();
    initDP_ = name;
    setVisible(false);
  }
  
  private List<DPPreview> getAvailableDPs() {
    List<DPPreview> list = new LinkedList<DPPreview>(); 
    File dataDir = new File(sysProps_.getProperty(SysProps.FP_HOME) + "data");
    
    File[] files = dataDir.listFiles();
    for (int i = 0; i < files.length; i++) {
      File file = files[i];
      if(file.isDirectory()) {
        String dpXmlFile = sysProps_.getProperty(SysProps.FP_HOME) + "data" + File.separator + file.getName() + File.separator + "datapackage.xml";
        if(new File(dpXmlFile).exists()) list.add(new DPPreview(file.getName()));
      }
    }
    
    return list;
  }

  private class DPPreview {
    String name_, desc_;
    
    public DPPreview(String name) {
      name_ = name;
      
      try {
        String filename = sysProps_.getProperty(SysProps.FP_HOME) + "data" + File.separator + name_ + File.separator + "datapackage.xml";
        DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = docBuilder.parse(filename);
        NodeList docNodes = doc.getChildNodes();
        Node topNode = docNodes.item(0);
        if (docNodes.getLength() != 1 && !topNode.getNodeName().equals("datapackage")) {
          System.out.println("Not a valid datapackage properties file");
          return;
        }
        desc_ = topNode.getAttributes().getNamedItem("desc").getNodeValue();
      } catch(Exception e) {
        e.printStackTrace();
      }
    }
    
    public String getName() { return name_; }

    public String getDesc() { return desc_; }
    
  }
  
  private class DPTable extends JTable {
    
    public DPTable() {
      super();

      setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      final ListSelectionModel rowLSM = getSelectionModel();
      rowLSM.addListSelectionListener(new ListSelectionListener() {

        public void valueChanged(ListSelectionEvent e) {
          if (e.getValueIsAdjusting()) return;
          if (!rowLSM.isSelectionEmpty()) proceedBtn_.setEnabled(true);
        }
      });

      addMouseListener(new MouseAdapter(){
        @Override
        public void mouseClicked(MouseEvent e){
          if(e.getClickCount() == 2) {
            StartupDialog.this.proceed();
          }
        }
      });

      updateData();
    }
    
    private void updateData() {

      List<DPPreview> dps = getAvailableDPs();
              
      String[] colNames = new String[2];
      colNames[0] = "Name";
      colNames[1] = "Description";

      String[][] table = new String[dps.size()][2];

      int r = 0;
      for (Iterator<DPPreview> it = dps.iterator(); it.hasNext();) {
        DPPreview dpp = it.next();
        table[r][0] = dpp.getName();
        table[r][1] = dpp.getDesc();        
        r++;
      }
      DefaultTableModel model = new UneditableTableModel(table, colNames);
      setModel(model);

    }
  }
}
